<template>
  <view class="home-container">
    <!-- 顶部蓝色背景和头部 -->
    <view class="header-bg">
      <view class="header-top">
        <view class="community">{{ currentCommunity }}</view>
        <view class="switch-btn" @click="openCommunityPopup">切换小区</view>
      </view>
      <image class="header-img" src="/static/home_top.png" mode="widthFix"></image>
      <view class="header-title">智慧物管</view>
      <view class="header-desc">让物业管理更轻松</view>
    </view>

    <!-- 公告栏 -->
    <view class="notice-bar">
      <image class="horn" src="/static/horn.png"></image>
      智慧物业体验版上线了，快来尝鲜呀~~
    </view>

    <!-- 今日巡更 -->
    <view class="patrol-box" @click="goToPatrol">
      <view class="patrol-title">今日巡更</view>
      <view class="patrol-desc">随时随地更新巡更概况</view>
      <view class="patrol-data">
        <view class="patrol-item">
          <view class="num">{{ patrolData.totalPoints }}</view>
          <view class="label">巡更点</view>
        </view>
        <view class="patrol-item">
          <view class="num">{{ patrolData.completedPoints }}</view>
          <view class="label">已巡更</view>
        </view>
        <view class="patrol-item">
          <view class="num">{{ patrolData.remainingPoints }}</view>
          <view class="label">未巡更</view>
        </view>
      </view>
      
      <!-- 巡更进度条 -->
      <view class="progress-bar-container">
        <view class="progress-bar">
          <view 
            class="progress-fill" 
            :style="{width: completionRate + '%'}"
          ></view>
        </view>
        <text class="progress-text">已完成 {{ completionRate }}%</text>
      </view>
    </view>

    <!-- 物业服务 -->
    <view class="service-section">
      <view class="service-title">
        <text class="blue-bar"></text>物业服务
      </view>
      <view class="service-grid">
        <view class="service-item pink">
          <text class="right-text">住户管理</text>
          <image src="/static/home_user.png" class="icon right-icon"></image>
        </view>
        <view class="service-item purple">
          <text class="right-text">投诉处理</text>
          <image src="/static/home_report.png" class="icon right-icon"></image>
        </view>
        <view class="service-item green" @click="goToRemoteDoor">
          <text class="right-text">远程开门</text>
          <image src="/static/home_door.png" class="icon right-icon"></image>
        </view>
        <view class="service-item blue" @click="goToWorkOrder">
          <text class="right-text">工单大厅</text>
          <image src="/static/home_work.png" class="icon right-icon"></image>
        </view>
      </view>
    </view>

    <!-- 小区切换弹窗 -->
    <uni-popup ref="communityPopup" type="bottom">
      <view class="community-popup-new">
        <view class="popup-header">
          <text class="popup-title">请选择小区</text>
          <text class="popup-close" @click="$refs.communityPopup.close()">×</text>
        </view>
        <view class="popup-list">
          <view
            v-for="item in communityList"
            :key="item.id"
            class="popup-item"
            :class="{ active: item.name === currentCommunity }"
            @click="selectCommunity(item)"
          >
            {{ item.name }}
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import request from '@/util/request.js'
export default {
  name: "HomePage",
  data() {
    return {
      currentCommunity: '阳光花园',
      communityList: [],
      patrolData: {
        totalPoints: 0,
        completedPoints: 0,
        remainingPoints: 0
      }
    }
  },
  computed: {
    // 计算完成率
    completionRate() {
      if (this.patrolData.totalPoints <= 0) return 0;
      const rate = Math.round((this.patrolData.completedPoints / this.patrolData.totalPoints) * 100);
      return Math.min(100, Math.max(0, rate)); // 确保在0-100范围内
    }
  },
  onLoad() {
    this.getPatrolData();
  },
  onShow() {
    // 每次页面显示时刷新数据，自动获取最新选择的小区ID
    this.getAllTaskList();
  },
  methods: {
    openCommunityPopup() {
      this.getCommunityList();
      this.$refs.communityPopup.open();
    },
    async getCommunityList() {
      try {
        // 尝试请求后端接口
        const res = await request({ url: 'property-server/communityList', method: 'GET' });
        if (res.code === 200) {
          this.communityList = res.data;
        } else {
          // 接口返回异常时用模拟数据
          uni.showToast({ title: '接口异常，请稍后再试', icon: 'none' });
        }
      } catch (e) {
        // 网络错误时用模拟数据
        uni.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
      }
    },
    // 获取今日巡更数据
    async getPatrolData() {
      try {
        const res = await request({ 
          url: 'patrol-server/patrolTask/todaySummary', 
          method: 'GET' 
        });
        
        if (res.code === 200 && res.data) {
          this.patrolData = {
            totalPoints: res.data.totalPoints || 0,
            completedPoints: res.data.completedPoints || 0,
            remainingPoints: (res.data.totalPoints || 0) - (res.data.completedPoints || 0)
          };
        } else {
          // 如果接口失败，使用模拟数据
          console.error('获取今日巡更数据失败', res);
          // 获取巡更任务列表，计算统计数据
          this.getPatrolDataFromTasks();
        }
      } catch (e) {
        console.error('获取今日巡更数据出错', e);
        // 获取巡更任务列表，计算统计数据
        this.getPatrolDataFromTasks();
      }
    },
    // 从巡更任务列表计算今日巡更数据
    async getPatrolDataFromTasks() {
      try {
        const res = await request({ 
          url: 'patrol-server/patrolTask/planList', 
          method: 'GET' 
        });
        
        if (res.code === 200 && res.data) {
          // 过滤今日任务
          const today = new Date().toISOString().split('T')[0]; // 获取今天的日期 YYYY-MM-DD
          const todayTasks = res.data.filter(item => {
            // 如果有taskDate字段且是今天的任务
            return item.taskDate && item.taskDate.includes(today);
          });
          
          // 计算完成的点位数量
          let completed = 0;
          let total = 0;
          
          todayTasks.forEach(task => {
            // 根据任务状态计算数据，状态2表示已完成
            if (task.taskStatus === 2) {
              completed += (task.pointCount || 0);
            }
            total += (task.pointCount || 0);
          });
          
          this.patrolData = {
            totalPoints: total,
            completedPoints: completed,
            remainingPoints: total - completed
          };
        } else {
          // 接口失败，使用默认值
          this.patrolData = {
            totalPoints: 25,
            completedPoints: 5,
            remainingPoints: 20
          };
        }
      } catch (e) {
        console.error('获取巡更任务列表出错', e);
        // 网络错误时使用默认值
        this.patrolData = {
          totalPoints: 25,
          completedPoints: 5,
          remainingPoints: 20
        };
      }
    },
    selectCommunity(item) {
      // 设置当前显示的小区名称
      this.currentCommunity = item.name;
      
      // 关闭弹窗
      this.$refs.communityPopup.close();
      
      // 将完整的小区对象保存到本地存储
      uni.setStorageSync('currentCommunityObj', item);
      
      // 单独保存小区ID，方便直接使用
      uni.setStorageSync('currentCommunityId', item.id);
      
      console.log('已选择小区:', item.name, '小区ID:', item.id);
      
      // 小区切换后，重新获取巡更数据
      this.getPatrolData();
    },
    goToWorkOrder() {
      uni.switchTab({
        url: '/pages/workorder/index'
      });
    },
    // 跳转到巡更页面
    goToPatrol() {
      uni.switchTab({
        url: '/pages/patrol/index'
      });
    },
    goToRemoteDoor() {
      uni.navigateTo({
        url: '/pages/remote-door/index'
      });
    }
  }
}
</script>

<style scoped>
.home-container {
  background: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}
.header-bg {
  background: linear-gradient(180deg, #1a7cf7 0%, #3bb3fa 100%);
  border-bottom-left-radius: 40rpx;
  border-bottom-right-radius: 40rpx;
  padding-bottom: 40rpx;
  position: relative;
}
.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 0 30rpx;
  color: #fff;
  font-size: 28rpx;
}
.header-img {
  width: 90%;
  margin: 30rpx 5% 0 5%;
  display: block;
}
.header-title {
  color: #fff;
  font-size: 40rpx;
  font-weight: bold;
  margin: 30rpx 0 10rpx 40rpx;
}
.header-desc {
  color: #e0e6ed;
  font-size: 24rpx;
  margin-left: 40rpx;
}
.notice-bar {
  background: #fff;
  margin: 30rpx 30rpx 0 30rpx;
  border-radius: 16rpx;
  padding: 16rpx 20rpx;
  display: flex;
  align-items: center;
  font-size: 26rpx;
  color: #1a7cf7;
  box-shadow: 0 2rpx 8rpx #e6e6e6;
}
.horn {
  width: 32rpx;
  height: 32rpx;
  margin-right: 10rpx;
}
.patrol-box {
  background: #2196f3;
  margin: 30rpx 30rpx 0 30rpx;
  border-radius: 20rpx;
  padding: 30rpx 0 30rpx 0;
  color: #fff;
  text-align: center;
}
.patrol-title {
  font-size: 32rpx;
  font-weight: bold;
}
.patrol-desc {
  font-size: 22rpx;
  margin: 10rpx 0 20rpx 0;
}
.patrol-data {
  display: flex;
  justify-content: space-around;
  margin-top: 10rpx;
}
.patrol-item .num {
  font-size: 36rpx;
  font-weight: bold;
}
.patrol-item .label {
  font-size: 22rpx;
  margin-top: 6rpx;
}
.service-section {
  margin: 40rpx 30rpx 0 30rpx;
}
.service-title {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}
.blue-bar {
  display: inline-block;
  width: 8rpx;
  height: 28rpx;
  background: #2196f3;
  border-radius: 4rpx;
  margin-right: 12rpx;
}
.service-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx 0;
  justify-content: space-between;
}
.service-item {
  width: 48%;
  height: 120rpx;
  border-radius: 16rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  padding: 0 30rpx 0 30rpx;
  box-sizing: border-box;
}
.right-icon {
  width: 64rpx;
  height: 64rpx;
  margin-left: 32rpx;
}
.right-text {
  font-size: 32rpx;
  font-weight: 500;
  flex: 1;
  text-align: left;
}
.pink { background: #ffe9e3; color: #ff7a45; }
.purple { background: #f0e9ff; color: #9254de; }
.green { background: #e6f7e6; color: #52c41a; }
.blue { background: #e6f0ff; color: #1890ff; }
.community-popup-new {
  background: #fff;
  border-top-left-radius: 32rpx;
  border-top-right-radius: 32rpx;
  box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
  padding-bottom: env(safe-area-inset-bottom);
  position: relative;
  min-height: 240rpx;
  padding-top: 0;
  padding-bottom: 0;
}
.popup-header {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 90rpx;
  border-bottom: 1px solid #f5f5f5;
}
.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #222;
}
.popup-close {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 48rpx;
  color: #bbb;
  font-weight: 400;
  line-height: 1;
  padding: 0 10rpx;
}
.popup-list {
  padding: 0 0 20rpx 0;
}
.popup-item {
  padding: 32rpx 0;
  text-align: center;
  font-size: 30rpx;
  color: #333;
  transition: background 0.2s;
}
.popup-item.active {
  color: #1a7cf7;
  font-weight: bold;
  background: #f0f7ff;
}
.popup-item:active {
  background: #f5f7fa;
}
.progress-bar-container {
  margin: 24rpx 30rpx 0;
  padding: 0 10rpx;
  display: flex;
  align-items: center;
}
.progress-bar {
  background: rgba(255,255,255,0.3);
  border-radius: 20rpx;
  height: 10rpx;
  overflow: hidden;
  flex: 1;
}
.progress-fill {
  background: #ffffff;
  border-radius: 20rpx;
  height: 100%;
  transition: width 0.5s ease-in-out;
}
.progress-text {
  margin-left: 20rpx;
  font-size: 24rpx;
  color: #ffffff;
  opacity: 0.9;
  width: 120rpx;
  text-align: right;
}
</style> 